// pages/repair/workEdit/edit.js
import WxValidate from '../../../utils/validate';
var app = getApp();
let urlIp = app.globalData.urlIp;
let uploadIp = urlIp + '/api/WeChat/upload'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winHeight: "",//窗口高度
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    count: 0, // 记录打开次数
    priorityArr: [
      { text: '普通', value: '0' },
      { text: '紧急', value: '1' },
      { text: '很紧急', value: '2' },],// 工单优先级
    priorIndex: 0, // 优先级索引
    workArr: [], //服务类型
    workIndex: 0,
    equipArr: [], // 设备类型
    equipIndex: 0,
    errorArr: [{ text: '否', value: 0 }, { text: '是', value: 1 },
    ], // 是否宕机
    errorIndex: 0,
    model: '', // 产品型号
    contacts: '', // 联系人
    phone: '', // 联系电话
    description: '', // 描述
    remark: "", // 备注
    isCheck: true, // 禁用全局
    isOrder: false, // 禁用服务类型
    content: {}, // 接收来的数据
    repairForm: {
      workOrderCode: '',
      priorIndex: '',
    }, // 表单数据
    /* 文件上传相关 */
    accessoryMedia: [], //附件媒体 真实上传的文件
    accessoryFile: [],  // 附件文件 真实上传的文件
    mediaArr: [],
    prevMedia: [],
    deleteIds: [],
  },
  priorChage(e) {
    this.setData({
      priorIndex: e.detail.value
    })
  },
  // 服务类型选择
  workChage(e) {
    this.setData({
      workIndex: e.detail.value
    })
  },
  // 设备选择
  equipChange(e) {
    let i = e.detail.value;
    let model = this.data.equipArr[i].model
    this.setData({
      equipIndex: i,
      model: model,
    })
  },
  // 宕机选择
  errorChage(e) {
    this.setData({
      errorIndex: e.detail.value
    })
  },
  // 权限控制
  manageControl() {
    // 控制外部按钮
    let isCheck = false
    // 控制表单填写
    if (this.data.content.typeName == "报修") {

      isCheck = true;

    } else {
      isCheck = false;
    }
    this.setData({

      isCheck: isCheck,
    })
  },
  // 设置优先级回显
  _setProity() {
    let pro = this.data.content.priority
    if (pro != undefined) {
      let index = this.data.priorityArr.findIndex((item) => {
        return item.value == pro
      })
      this.setData({
        priorIndex: index
      })
    } else {
      return
    }
  },
  // 设置是否宕机
  _setDown() {
    const { isDown } = this.data.content;
    let index = 0
    if (isDown) {
      index = 1
    }
    this.setData({
      errorIndex: index
    })
  },
  // 获取设备编号
  _getEquip() {
    let { code } = this.data.content
    let id = this.Store.getItem("userid");
    this.axios.custom("AllInstalledProducts", "serialOrLotNumbersAndModel", {
      id: id,
    })
      .then((res) => {
        if (res.code == '200') {
          if (res.data.length) {
            let index = res.data.findIndex((item) => {
              return item.serialOrLotNumber == code
            })
            let model = res.data[index].model
            this.setData({
              equipArr: res.data,
              model: model,
              equipIndex: index
            })
          }
        } else {

        }
        console.log(res, '设备编号')
      });
  },
  // 获取工单类型
  _getWorkType() {
    let { type } = this.data.content;
    this.axios.query("SystemEnum", {}, { typeValue: "repair_work_order_type" })
      .then((res) => {
        if (res.code == '200') {
          if (res.data.rows.length) {
            let index = res.data.rows.findIndex((item) => {
              return item.value == type
            })
            this.setData({
              workArr: res.data.rows,
              workIndex: index,
            })
          }
        } else {

        }
        console.log(res, "工单");
      });
  },
  // 获取工单详情
  _getCheck() {
    const { id } = this.data.content;
    let accessoryMedia = [];
    let accessoryFile = [];
    let mediaArr = [];
    let prevMedia = [];
    this.axios
      .getObject("RepairWorkOrder", id)
      .then((res) => {
        if (res.code == '200') {
          // 过滤文件 
          let fileTypes = ['pdf', 'pptx', 'ppt', 'xlsx', 'xls', 'docx', 'doc', 'txt', 'zip'];
          let imgTypes = ["jpg", "jpeg", "png", "gif"];
          let videoTyeps = ['mpeg4', 'mp4', 'rmvb', 'swf', 'ogg', 'avi', 'flv'];
          let fileArr = res.data.repairWorkOrderFileViewModelList
          fileArr.forEach((item) => {
            let type = item.fileType.toLowerCase()

            if (fileTypes.indexOf(type) > -1) {
              accessoryFile.push(item);
            } else {
              mediaArr.push(item)
              accessoryMedia.push(item);
              // 预览音视频
              let obj = {}
              obj.url = urlIp + item.path;
              if (imgTypes.indexOf(type) > -1) {
                item.prePath = urlIp + item.path;
                obj.type = 'image'
              }
              if (videoTyeps.indexOf(type) > -1) {
                item.prePath = '';
                obj.type = 'video'
              }
              prevMedia.push(obj)
            }

          })


          this.setData({
            repairForm: res.data,
            logArr: res.data.repairWorkOrderAcceptanceList,
            piepleArr: res.data.personInformationList,
            mediaArr: mediaArr,
            prevMedia: prevMedia,
            accessoryMedia,
            accessoryFile,
          })
        }
        // 日志和 人员信息
        console.log("测试", res);
      })
      .catch((e) => {
        console.log(e);
      });
  },
  // 提交数据
  submit(e) {
    let cache = e.detail.value
    let { accessoryMedia, accessoryFile, deleteIds } = this.data
    if (!this.WxValidate.checkForm(e.detail.value)) {
      let msg = this.WxValidate.errorList[0];
      this.showModal(msg);
      return false
    }
    cache.isDown = Boolean(cache.isDownTrans);
    let form = this.data.repairForm;
    cache = Object.assign(form, cache)
    // 处理文件
    // 合并文件资源和视频资源
    let accessory = accessoryMedia.concat(accessoryFile)
    console.log(accessory, '合并后的文件')
    // 过滤已有图片
    accessory = this.filterNew(accessory);
    cache.base64s = accessory.map((item) => {
      item = item.base64;
      return item;
    });
    cache.fileTypes = accessory.map((item) => {
      item = item.fileType;
      return item;
    });
    cache.fileNames = accessory.map((item) => {
      item = item.fileNames;
      return item;
    });
    cache.deleteIds = deleteIds;
    console.log(cache, '函数应该是通用的')
    this._edit(cache);
  },
  // 展示弹框
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  // 提交
  _edit(data) {
    let params = data;
    this.axios.update("RepairWorkOrder", params)
      .then((res) => {
        let that = this // 缓存作用域
        // 添加成功跳转到详情页
        wx.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 2000,
          success() {
            that.Router.push({
              path: 'workLog',
              query: {},
              openType: 'reLaunch'
            });
            console.log('准备跳转')
          }
        })
        console.log(res);

      })
      .catch((response) => {

      });
  },
  // 校检规则
  initValidate() {
    const rules = {
      type: {
        required: true,
      },
      contacts: {
        required: true,
      },
      phone: {
        required: true,
      },
      isDownTrans: {
        required: true,
      },
      description: {
        required: true,
      },
    }
    const messages = {
      type: {
        required: '请选择服务类型',
      },
      contacts: {
        required: '请输入联系人',
      },
      phone: {
        required: '请输入联系电话',
      },
      isDownTrans: {
        required: '请选择是否宕机',
      },
      description: {
        required: '请输入故障描述',
      },
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  init() {
    this._getEquip();
    this._getWorkType();
    this._getCheck();
    this._setProity();
    this._setDown();
   // this.manageControl();
    this.initValidate();
  },

  /* 文件上传 */

  // 图片视频上传
  carama() {
    let { mediaArr, prevMedia } = this.data
    let that = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: async res => {
        // 用于上传
        let tempFilePaths = res.tempFiles
        // 组装原始数据
        let tempArr = res.tempFiles
        if (res.type == 'image') {
          tempArr.forEach((item) => {
            item.prePath = item.tempFilePath
            item.type = 'image'
          })
        } else {
          tempArr.forEach((item) => {
            item.prePath = item.thumbTempFilePath
            item.type = 'video'
          })
        }
        // 组装预览数据
        let cacheMedia = []
        tempArr.forEach((item) => {
          let obj = {}
          obj.url = item.tempFilePath;
          obj.type = item.type;
          cacheMedia.push(obj)
        })
        mediaArr = mediaArr.concat(tempArr)

        prevMedia = prevMedia.concat(cacheMedia);
        //上传图片
        wx.uploadFile({
          url: uploadIp, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0].tempFilePath,
          name: 'file',
          formData: {
            'user': 'test'
          },
          success(res) {
            const data = JSON.parse(res.data);
            if (data.code == '200') {
              let cache = data.data
              cache.fileType = cache.fileExtension.slice(1);
              cache.fileNames = cache.path.slice(0, -5);
              that.data.accessoryMedia.push(cache);
              console.log(data, '上传之后的返回值')
              //do something 成功再更新
              that.setData({
                mediaArr: mediaArr,
                prevMedia,
              })
            } else {
              console.log('报错')
            }

          },
          complete(res) {
            console.log(res)
          },
          fail(res) {
            console.log(res)
          }
        })
      }
    })
  },
  // 图片视频删除
  deleteMediaBtn(e) {
    console.log(e)
    let i = e.target.id
    let prevMedia = this.data.prevMedia;
    let mediaArr = this.data.mediaArr;
    console.log(i)
    let accessoryMedia = this.data.accessoryMedia
    console.log(i)
    // 这里可能要更新进删除的数组
    if (accessoryMedia[i].fileId) {
      this.data.deleteIds.push(accessoryMedia[i].fileId);
    }
    accessoryMedia.splice(i, 1);
    prevMedia.splice(i, 1);
    mediaArr.splice(i, 1);
    this.setData({
      prevMedia,
      mediaArr
    })
  },
  // 图片和视频预览
  prewMedia(e) {
    let current = Number(e.target.id)
    console.log(current);
    let { prevMedia } = this.data
    console.log(prevMedia)
    wx.previewMedia({
      current: current, // 当前显示图片的http链接
      sources: prevMedia,// 需要预览的图片http链接列表
      success: (res) => {
        console.log('调用成功', res)
      },
      fail: (res) => {
        console.log('调用成功', res);
      }
    })
    console.log(e, '点击上传视频文件')
  },

  /*文件上传 */
  // 文件上传
  uploadFile(e) {
    let { accessoryFile } = this.data;
    let that = this;
    wx.chooseMessageFile({
      count: 1, // 最多选取的数量
      type: 'file', // all 所有文件选择， video, image, file
      success: async res => {
        const tempFiles = res.tempFiles;  // 文件的临时路径
        // 检测文件大小
        console.log(tempFiles[0].path);
        let name = tempFiles[0].name.slice(0, -5)

        wx.uploadFile({
          url: uploadIp, //仅为示例，非真实的接口地址
          filePath: tempFiles[0].path,
          name: 'file',
          formData: {
            realFileName: name
          },
          success(res) {
            const data = JSON.parse(res.data);
            if (data.code == '200') {
              console.log(data, '接收数据')
              let cache = data.data
              cache.fileType = cache.fileExtension.slice(1);
              cache.fileNames = cache.fileName;
              accessoryFile.push(cache)
              that.setData({
                accessoryFile,
              })
            } else {
              console.log('服务器报错')
            }
          },
          complete(res) {
            console.log(res)
          },
          fail(res) {
            console.log(res)
          }
        })
        // 可以进行上传

        console.log(tempFiles)
      },
      fail: err => {
        console.log(err);
      }
    });

    console.log(e, '测试')
  },
  // 删除文件
  deleteFileBtn(e) {
    console.log(e)
    let i = e.target.id
    let accessoryFile = this.data.accessoryFile
    console.log(i)
    // 这里可能要更新进删除的数组
    if (accessoryFile[i].fileId) {
      this.data.deleteIds.push(accessoryFile[i].fileId);
    }
    accessoryFile.splice(i, 1);
    this.setData({
      accessoryFile
    })
  },
  // 文件预览
  prewFile(e) {
    let i = Number(e.target.id)
    let accessoryFile = this.data.accessoryFile
    let url = urlIp + accessoryFile[i].path;
    let type = accessoryFile[i].fileType
    console.log(url, type);
    wx.downloadFile({
      url: url,
      header: {},
      success: function (res) {
        var filePath = res.tempFilePath;
        console.log(filePath);
        wx.openDocument({
          filePath: filePath,
          fileType: type,
          showMenu: true,
          success: function (res) {
            console.log(res)
          },
          fail: function (res) {
            wx.showToast
            console.log(res, '失败')
          },
          complete: function (res) {
            console.log(res, '成功')
          }
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '简历异常，无法打开',
          icon: 'none'
        })
      },
      complete: function (res) { },
    })
  },

  // 过滤新增图片
  filterNew(arr) {
    let cache = arr.filter((item) => {
      if (!item.fileId) {
        return item;
      }
    });
    console.log(arr, '新增的文件');
    return cache;
  },
  // 处理图片
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 140;
        console.log(calc)
        that.setData({
          winHeight: calc
        });
      }
    });
    const eventChannel = this.getOpenerEventChannel();
    // 监听 index页面定义的toHome 事件
    eventChannel.on('toWorkEdit', (res) => {
      this.setData({
        content: res
      })

      console.log(res, '把文件转换为可用文件')
      // 过滤文件格式 图片和文件格式分离
      this.init();
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})